import 'dart:convert';
import 'dart:developer' as developer;
import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'cn_chartRechargeCard_message.dart';
// import 'package:get/route_manager.dart';
import 'package:rongcloud_im_wrapper_plugin/rongcloud_im_wrapper_plugin.dart';

// import '../../util/file.dart';
import 'cn_media_util.dart';
import 'cn_style.dart';
import 'cn_cached_image_widget.dart';
import 'cn_common_global.dart';
import 'cn_event_bus.dart';
import 'package:url_launcher/url_launcher.dart';
// import '../../../../generated/l10n.dart';

class CnMessageItemFactory extends StatefulWidget {
  final String pageName = "example.CnMessageItemFactory";
  final RCIMIWMessage? message;
  final bool needShow;
  const CnMessageItemFactory({Key? key, this.message, this.needShow = true})
      : super(key: key);

  @override
  State<CnMessageItemFactory> createState() => _CnMessageItemFactoryState();
}

class _CnMessageItemFactoryState extends State<CnMessageItemFactory> {
  bool isPlayAudio = false;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // setState(() {
    //   isPlayAudio = true;
    // });
    double screenWidth = MediaQuery.of(context).size.width;
    return Container(
      color: _getMessageWidgetBGColor(widget.message!.direction!.index),
      child: messageItem(context),
    );
  }

  ///文本消息 item
  Widget textMessageItem(BuildContext context) {
    double screenWidth = MediaQuery.of(context).size.width;
    RCIMIWTextMessage? msg = widget.message! as RCIMIWTextMessage?;

    bool hyperlink = false;
    bool rechargeInvitation = false;
    String url = '';
    if (msg!.text!.contains('https') && msg!.text!.contains('↑')) {
      hyperlink = true;

      url = msg!.text!.substring(msg!.text!.indexOf('https'));
      url = url.split('↑')[0];
    }

    if (msg.extra != null && msg.extra!.contains('invitationId')) {
      rechargeInvitation = true;
    }

    List textList = msg!.text!.split(url);

    return Container(
        constraints: BoxConstraints(
          // 屏幕宽度减去头像宽度加上间距
          maxWidth: screenWidth - 150,
        ),
        padding: EdgeInsets.all(10),
        child: hyperlink
            ? Container(
                child: Text.rich(
                  TextSpan(
                    children: [
                      TextSpan(
                        text: textList[0],
                        style: TextStyle(fontSize: RCFont.MessageTextFont),
                      ),
                      TextSpan(
                          text: url,
                          style: TextStyle(
                              color: Colors.red,
                              fontSize: RCFont.MessageTextFont),
                          recognizer: TapGestureRecognizer()
                            ..onTap = () {
                              print('点击文字触发方法,打开网址');
                              _launchInBrowser(Uri.parse(url));
                            }),
                      TextSpan(
                        text: textList[1],
                        style: TextStyle(fontSize: RCFont.MessageTextFont),
                      ),
                    ],
                  ),
                ),
              )
            : Text(
                widget.needShow ? msg!.text! : "",
                style: TextStyle(
                  fontSize: RCFont.MessageTextFont,
                  color: rechargeInvitation ? Colors.blue : Colors.black,
                  decoration: rechargeInvitation
                      ? TextDecoration.underline
                      : TextDecoration.none,
                ),
              ));
  }

  ///图片消息 item
  ///优先读缩略图，否则读本地路径图，否则读网络图
  Widget imageMessageItem(BuildContext context) {
    RCIMIWImageMessage? msg = widget.message! as RCIMIWImageMessage?;

    Widget widgetNew;
    if (widget.needShow) {
      if (msg!.thumbnailBase64String != null &&
          msg.thumbnailBase64String!.length > 0) {
        Uint8List bytes = base64.decode(msg.thumbnailBase64String!);
        widgetNew = Image.memory(bytes);
        if (msg.local == null) {
          CnGlobal.engine.downloadMediaMessage(msg);
        }
      } else {
        if (msg.local != null) {
          String path = CnMediaUtil.instance!.getCorrectedLocalPath(msg.local)!;
          File file = File(path);
          if (file != null && file.existsSync()) {
            widgetNew = Image.file(file);
          } else {
            CnGlobal.engine.downloadMediaMessage(msg);
            // RongIMClient.downloadMediaMessage(message!);
            // widget = Image.network(msg.imageUri);
            widgetNew = CnCachedNetworkImage(
              progressIndicatorBuilder: (context, url, progress) =>
                  CircularProgressIndicator(
                value: progress!.progress,
              ),
              imageUrl: msg.remote!,
            );
          }
        } else {
          CnGlobal.engine.downloadMediaMessage(msg);
          // widget = Image.network(msg.imageUri);
          widgetNew = CnCachedNetworkImage(
            progressIndicatorBuilder: (context, url, progress) =>
                CircularProgressIndicator(
              value: progress!.progress,
            ),
            imageUrl: msg.remote!,
          );
        }
      }
    } else {
      widgetNew = Stack(
        children: <Widget>[
          Image.asset(
            widget.message!.direction == RCIMIWMessageDirection.send
                ? "images/message/burnPicture.png"
                : "images/message/burnPictureForm.png",
            width: 120,
            height: 126,
          ),
          Container(
            child: Text(
              "点击查看",
            ),
            height: 126,
            width: 120,
            alignment: Alignment.bottomCenter,
          )
        ],
      );
    }

    return Container(
      constraints: BoxConstraints(
        maxWidth: MediaQuery.of(context).size.width - 150,
      ),
      child: widgetNew,
    );
  }

  ///动图消息 item
  Widget gifMessageItem(BuildContext context) {
    RCIMIWGIFMessage? msg = widget.message as RCIMIWGIFMessage?;
    Widget? widget_new;
    if (widget.needShow) {
      if (msg!.local != null) {
        String path = CnMediaUtil.instance!.getCorrectedLocalPath(msg.local)!;
        File file = File(path);
        if (file != null && file.existsSync()) {
          widget_new = Image.file(file);
        } else {
          // 没有 localPath 时下载该媒体消息，更新 localPath
          CnGlobal.engine.downloadMediaMessage(msg);
          widget_new = Image.network(
            msg.remote!,
            fit: BoxFit.cover,
            loadingBuilder: (BuildContext context, Widget child,
                ImageChunkEvent? loadingProgress) {
              if (loadingProgress == null) return child;
              return Center(
                child: CircularProgressIndicator(
                  value: loadingProgress.expectedTotalBytes != null
                      ? loadingProgress.cumulativeBytesLoaded /
                          loadingProgress.expectedTotalBytes!
                      : null,
                ),
              );
            },
          );
        }
      } else if (msg.remote != null) {
        CnGlobal.engine.downloadMediaMessage(msg);
        widget_new = Image.network(
          msg.remote!,
          fit: BoxFit.cover,
          loadingBuilder: (BuildContext context, Widget child,
              ImageChunkEvent? loadingProgress) {
            if (loadingProgress == null) return child;
            return Center(
              child: CircularProgressIndicator(
                value: loadingProgress.expectedTotalBytes != null
                    ? loadingProgress.cumulativeBytesLoaded /
                        loadingProgress.expectedTotalBytes!
                    : null,
              ),
            );
          },
        );
      } else {
        developer.log("GifMessage localPath && remoteUrl is null",
            name: widget.pageName);
      }

      double screenWidth = MediaQuery.of(context).size.width;
      if (msg.width != null &&
          msg.height != null &&
          msg.width! > 0 &&
          msg.height! > 0 &&
          msg.width! > screenWidth / 3) {
        return Container(
          width: msg.width!.toDouble() / 3,
          height: msg.height!.toDouble() / 3,
          child: widget,
        );
      }
    } else {
      widget_new = Stack(
        children: <Widget>[
          Image.asset(
            widget.message!.direction == RCIMIWMessageDirection.send
                ? "images/message/burnPicture.png"
                : "images/message/burnPictureForm.png",
            width: 120,
            height: 126,
          ),
          Container(
            child: Text(
              "点击查看",
            ),
            height: 126,
            width: 120,
            alignment: Alignment.bottomCenter,
          )
        ],
      );
    }
    return widget;
  }

  ///语音消息 item
  Widget voiceMessageItem(context) {
    RCIMIWVoiceMessage? msg = widget.message! as RCIMIWVoiceMessage?;
    double screenWidth = MediaQuery.of(context).size.width;
    List<Widget> list = [];
    double widthValue = 20 + msg!.duration!.toDouble();
    widthValue =
        widthValue > (screenWidth - 200) ? (screenWidth - 200) : widthValue;
    if (widget.message!.direction == RCIMIWMessageDirection.send) {
      list.add(SizedBox(
        width: 10,
      ));
      list.add(Container(
        width: widthValue + 20,
        child: Text(
          msg!.duration.toString() + "''",
          style: TextStyle(fontSize: RCFont.MessageTextFont),
        ),
      ));
      // list.add(SizedBox(
      //   width: widthValue ,
      // ));
      list.add(Container(
        width: 20,
        height: 20,
        child: Image.asset(this.isPlayAudio
            ? "images/message/voicePlay_right.gif"
            : "images/message/voice_icon.png"),
      ));
    } else {
      list.add(SizedBox(
        width: 10,
      ));
      list.add(Container(
        width: 20,
        height: 20,
        child: Image.asset(this.isPlayAudio
            ? "images/message/voicePlay_left.gif"
            : "images/message/voice_icon_reverse.png"),
      ));
      // list.add(SizedBox(
      //   width: widthValue,
      // ));
      list.add(Container(
        width: widthValue + 20,
        child: Text(
          msg!.duration.toString() + "''",
          style: TextStyle(fontSize: RCFont.MessageTextFont),
        ),
      ));
    }

    return Container(
        width: 60 + widthValue,
        height: 44,
        child: GestureDetector(
          onTap: () {
            playAudio();
            setState(() {
              isPlayAudio = true;
            });
          },
          child: Row(children: list),
        ));
  }

  void playAudio() async {
    RCIMIWVoiceMessage msg = widget.message as RCIMIWVoiceMessage;
    if (msg.local != null &&
        msg.local!.isNotEmpty &&
        File(msg.local!).existsSync()) {
      CnMediaUtil.instance!.startPlayAudioFile(msg.local!, () {
        if (mounted) {
          setState(() {
            isPlayAudio = false;
          });
        }
      });
    } else if (msg.remote != null && msg.remote!.isNotEmpty) {
      CnMediaUtil.instance!.startPlayAudioUrl(msg.remote!, () {
        if (mounted) {
          setState(() {
            isPlayAudio = false;
          });
        }
      });

      RCIMIWDownloadMediaMessageListener? listener =
          RCIMIWDownloadMediaMessageListener(onMediaMessageDownloading:
              (RCIMIWMediaMessage? message, int? progress) {
//...
      }, onDownloadingMediaMessageCanceled: (RCIMIWMediaMessage? message) {
//...
      }, onMediaMessageDownloaded: (int? code, RCIMIWMediaMessage? message) {
//...
        print(code);
        print(message!.remote! + message.local!);
        if (message.remote!.isNotEmpty) {}
      });

      int? ret =
          await CnGlobal.engine!.downloadMediaMessage(msg, listener: listener);
    }
  }

  //充值消息 item
  Widget rechargeMessageItem(BuildContext context) {
    CnRCIMDChartRechargeCardMessage msg =
        widget.message! as CnRCIMDChartRechargeCardMessage;
    double screenWidth = MediaQuery.of(context).size.width;
    return Container(
        constraints: BoxConstraints(
          // 屏幕宽度减去头像宽度加上间距
          maxWidth: 220,
        ),
        padding: EdgeInsets.all(15),
        child: Column(children: <Widget>[
          Text(
            widget.needShow ? msg.tppTitle! : "",
            style: TextStyle(fontSize: RCFont.MessageRechargeTextFont),
          ),
          SizedBox(
            height: 10,
          ),
          ClipRRect(
              borderRadius: BorderRadius.circular(10),
              child: Image.network(
                msg.tppImageUrl!,
                width: 200,
                height: 200 * 9 / 16,
                fit: BoxFit.fill,
                loadingBuilder: (BuildContext context, Widget child,
                    ImageChunkEvent? loadingProgress) {
                  if (loadingProgress == null) return child;
                  return Center(
                    child: CircularProgressIndicator(
                      value: loadingProgress.expectedTotalBytes != null
                          ? loadingProgress.cumulativeBytesLoaded /
                              loadingProgress.expectedTotalBytes!
                          : null,
                    ),
                  );
                },
              )),
          SizedBox(
            height: 10,
          ),
          Container(
            child: Text(
              'click to check details',
              style: const TextStyle(color: Color(RCColor.MessageTimeBgColor)),
            ),
            height: 15,
            width: screenWidth - 170,
            alignment: Alignment.centerLeft,
          )
        ]));
  }

  // 引用消息 item
  Widget referenceMessageItem(BuildContext context) {
    RCIMIWReferenceMessage msg = widget.message! as RCIMIWReferenceMessage;
    double screenWidth = MediaQuery.of(context).size.width;
    return Container(
        width: screenWidth - 140,
        child: Column(children: <Widget>[
          Container(
            padding: EdgeInsets.fromLTRB(10, 4, 10, 4),
            alignment: Alignment.centerLeft,
            child: referenceWidget(msg),
          ),
          Container(
            margin: EdgeInsets.fromLTRB(10, 4, 10, 0),
            width: double.infinity,
            height: 1.0,
            color: Color(0xFFF3F3F3),
          ),
          Container(
            margin: EdgeInsets.fromLTRB(10, 4, 10, 10),
            alignment: Alignment.centerLeft,
            child: Text(msg.text!,
                textAlign: TextAlign.left,
                style: TextStyle(
                    fontSize: RCFont.MessageReferenceTitleFont,
                    color: Colors.black)),
          ),
        ]));
  }

  // 被引用的消息 UI
  Widget? referenceWidget(RCIMIWReferenceMessage msg) {
    if (msg is RCIMIWTextMessage) {
      RCIMIWTextMessage textMessage = msg.referenceMessage as RCIMIWTextMessage;
      return Text("${msg.senderUserId}:\n\n${textMessage.text}",
          textAlign: TextAlign.left,
          style: TextStyle(
              fontSize: RCFont.MessageReferenceContentFont,
              color: Color(RCColor.ConReferenceMsgContentColor)));
    } else if (msg.referenceMessage is RCIMIWImageMessage) {
      RCIMIWImageMessage imageMessage =
          msg.referenceMessage as RCIMIWImageMessage;
      Widget widget;
      if (imageMessage.thumbnailBase64String != null &&
          imageMessage.thumbnailBase64String!.length > 0) {
        Uint8List bytes = base64.decode(imageMessage.thumbnailBase64String!);
        widget = Image.memory(bytes);
      } else {
        if (imageMessage.local != null) {
          String path =
              CnMediaUtil.instance!.getCorrectedLocalPath(imageMessage.local)!;
          File file = File(path);
          if (file != null && file.existsSync()) {
            widget = Image.file(file);
          } else {
            // widget = Image.network(msg.imageUri);
            widget = CnCachedNetworkImage(
              progressIndicatorBuilder: (context, url, progress) =>
                  CircularProgressIndicator(
                value: progress!.progress,
              ),
              imageUrl: imageMessage.remote!,
            );
          }
        } else {
          // widget = Image.network(msg.imageUri);
          widget = CnCachedNetworkImage(
            progressIndicatorBuilder: (context, url, progress) =>
                CircularProgressIndicator(
              value: progress!.progress,
            ),
            imageUrl: imageMessage.remote!,
          );
        }
      }
      return widget;
    }
    //  else if (msg.referMsg is FileMessage) {
    //   FileMessage fileMessage = msg.referMsg as FileMessage;
    //   return Text("${msg.referMsgUserId}:\n\n[文件] ${fileMessage.mName}", textAlign: TextAlign.left, style: TextStyle(fontSize: RCFont.MessageReferenceContentFont, color: Color(RCColor.ConReferenceMsgContentColor)));
    // } else if (msg.referMsg is RichContentMessage) {
    //   RichContentMessage richContentMessage = msg.referMsg as RichContentMessage;
    //   return Text("${msg.referMsgUserId}:\n\n[图文] ${richContentMessage.title}", textAlign: TextAlign.left, style: TextStyle(fontSize: RCFont.MessageReferenceContentFont, color: Color(RCColor.ConReferenceMsgContentColor)));
    // }
  }

  Widget? messageItem(BuildContext context) {
    if (widget.message! is RCIMIWTextMessage) {
      return textMessageItem(context);
    } else if (widget.message! is RCIMIWImageMessage) {
      return imageMessageItem(context);
    } else if (widget.message! is RCIMIWVoiceMessage) {
      return voiceMessageItem(context);
    } else if (widget.message! is CnRCIMDChartRechargeCardMessage) {
      return rechargeMessageItem(context);
    }
    //  else if (message!.content is SightMessage) {
    //   return sightMessageItem();
    // } else if (message!.content is FileMessage) {
    //   return fileMessageItem(context);
    // } else if (message!.content is RichContentMessage) {
    //   return richContentMessageItem(context);
    // } else if (message!.content is GifMessage) {
    //   return gifMessageItem(context);
    // } else if (message!.content is CombineMessage) {
    //   return combineMessageItem(context);
    // }
    else if (widget.message! is RCIMIWReferenceMessage) {
      return referenceMessageItem(context);
    }
    // else if (message!.content is LocationMessage) {
    //   LocationMessage msg = message!.content as LocationMessage;
    //   return Text("位置消息 " + msg.mPoi!);
    // } else if (message!.content is GroupNotificationMessage) {
    //   GroupNotificationMessage groupNotificationMessage = message!.content as GroupNotificationMessage;
    //   return Text("群通知消息 ${groupNotificationMessage.operatorUserId} ${groupNotificationMessage.operation} ${groupNotificationMessage.data}");
    // }
    else {
      return Text("无法识别消息 " + widget.message!.targetId!);
    }
  }

  Future<void> _launchInBrowser(Uri url) async {
    if (!await launchUrl(
      url,
      mode: LaunchMode.externalApplication,
    )) {
      // throw Exception('Could not launch $url');
    }
  }

  Color _getMessageWidgetBGColor(int? messageDirection) {
    Color color = Color(RCColor.MessageSendBgColor);
    if (widget.message!.direction == RCIMIWMessageDirection.receive) {
      color = Color(RCColor.MessageReceiveBgColor);
    }
    return color;
  }
}
